package com.geekstudy.week2.controller;

import com.geekstudy.week2.configuration.DemoServletRequestConfiguration;
import org.apache.commons.configuration.web.ServletRequestConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * http://127.0.0.1:9102/week2/hello?name=demo
 * http://127.0.0.1:9102/week2/hello?name=demo&id=2021
 *
 *
 * https://cloud.tencent.com/developer/article/1588518
 * [享学Netflix] 一、Apache Commons Configuration：你身边的配置管理专家
 *
 * http://commons.apache.org/proper/commons-configuration/javadocs/v1.10/apidocs/index.html
 * https://mvnrepository.com/artifact/commons-configuration/commons-configuration/1.10
 *
 */

@RestController
public class Week2HelloController {

    final Logger logger = LoggerFactory.getLogger(Week2HelloController.class);

    @RequestMapping(path = "/week2/hello")
    public Map<String, String> hello(@RequestParam(name = "name") String name, HttpServletRequest httpRequest) {
        logger.info(" name:{} ", name);
        Map<String, String> resultMap = new LinkedHashMap<String, String>();

        resultMap.put("name", name);
        resultMap.put("message", "Hello, " + name);

        // 使用 ServletRequestConfiguration
        ServletRequestConfiguration servletRequestConfiguration = new ServletRequestConfiguration(httpRequest);
        Iterator<String> iterator = servletRequestConfiguration.getKeys();
        Map<String, String> keyValueMap = new LinkedHashMap<String, String>();
        for(;iterator.hasNext();) {
            String key = iterator.next();
            String value = servletRequestConfiguration.getString(key);
            keyValueMap.put(key, value);
        }
        logger.info("ServletRequestConfiguration requestKeyValue : {} ", keyValueMap.toString());

        // 使用 DemoServletRequestConfiguration
        DemoServletRequestConfiguration demoServletRequestConfiguration = new DemoServletRequestConfiguration(httpRequest);
        List<String> parameterNameList = demoServletRequestConfiguration.parameterNameList();
        logger.info("DemoServletRequestConfiguration parameterNameList:{} ", parameterNameList);
        Map<String, String> parameterFlatMap = demoServletRequestConfiguration.parameterFlatMap();
        logger.info("DemoServletRequestConfiguration parameterFlatMap:{} ", parameterFlatMap);


        return resultMap;
    }
}
